package com.wuliu.system.service.applet.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.wuliu.common.core.domain.PageResult;
import com.wuliu.common.core.domain.entity.BasCust;
import com.wuliu.common.core.domain.entity.SysDept;
import com.wuliu.common.exception.ServiceException;
import com.wuliu.common.utils.DateUtils;
import com.wuliu.common.utils.SecurityUtils;
import com.wuliu.common.utils.StringUtils;
import com.wuliu.system.domain.*;
import com.wuliu.system.domain.dto.applet.OpDrivingRecordDto;
import com.wuliu.system.domain.dto.applet.QryDrivingRecordDto;
import com.wuliu.system.domain.dto.applet.TspDrivingRecordDto;
import com.wuliu.system.domain.vo.applet.ExportDrivingRecordVo;
import com.wuliu.system.domain.vo.applet.TspDrivingRecordCountVo;
import com.wuliu.system.domain.vo.applet.TspDrivingRecordVo;
import com.wuliu.system.mapper.*;
import com.wuliu.system.service.IBasFilesService;
import com.wuliu.system.service.ITspDrivingDeptService;
import com.wuliu.system.service.applet.AppletTspDrivingRecordService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author realue
 * @version 1.0
 * @date 2023-11-04 16:11
 */
@Service
public class AppletTspDrivingRecordServiceImpl extends ServiceImpl<TspDrivingRecordMapper, TspDrivingRecord> implements AppletTspDrivingRecordService {
    @Resource
    private TspDrivingRecordMapper tspDrivingRecordMapper;
    @Resource
    private ITspDrivingDeptService tspDrivingDeptService;
    @Resource
    private TspDrivingDeptMapper tspDrivingDeptMapper;
    @Resource
    private IBasFilesService basFilesService;
    @Resource
    private BasFilesMapper basFilesMapper;
    @Resource
    private TspDrivingTrackMapper tspDrivingTrackMapper;
    @Resource
    private SysDeptMapper sysDeptMapper;

    /**
     * 查询行车记录
     *
     * @param id 行车记录主键
     * @return 行车记录
     */
    @Override
    public TspDrivingRecordVo selectTspDrivingRecordById(String id) {
        TspDrivingRecordVo recordVo = new TspDrivingRecordVo();
        TspDrivingRecord tspDrivingRecord = tspDrivingRecordMapper.selectTspDrivingRecordById(id);
        BeanUtil.copyProperties(tspDrivingRecord, recordVo);
        List<TspDrivingDept> drivingDepts = tspDrivingDeptMapper.selectList(new LambdaQueryWrapper<TspDrivingDept>()
                .eq(TspDrivingDept::getRecordId, id).orderByAsc(TspDrivingDept::getSortNo));
        recordVo.setTspDrivingDepts(drivingDepts);
        return recordVo;
    }

    /**
     * 查询行车记录列表
     *
     * @param dto 行车记录
     * @return 行车记录
     */
    @Override
    public PageResult<TspDrivingRecordVo> selectTspDrivingRecordList(QryDrivingRecordDto dto) {
        BasCust cust = SecurityUtils.getBasCust();
        QueryWrapper<TspDrivingRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("sys_account", cust.getSysAccount())
                .eq("cust_id", cust.getId());
        if (dto.getStatus() != 0) {
            wrapper.eq("status", dto.getStatus());
        }
        if (StringUtils.isNotEmpty(dto.getBeginDt())) {
            wrapper.ge("driving_date", dto.getBeginDt());
        }
        if (StringUtils.isNotEmpty(dto.getEndDt())) {
            wrapper.le("driving_date", dto.getEndDt() + " 23:59:59");
        }
        if (StringUtils.isNotEmpty(dto.getKeyWord())) {
            wrapper.and(qw -> qw.eq("driver_name", dto.getKeyWord()).or()
                    .eq("driver_mobile", dto.getKeyWord()).or()
                    .eq("vehicel_number", dto.getKeyWord()).or()
                    .eq("driving_no", dto.getKeyWord()));
        }
        wrapper.orderByDesc("create_time");
        Page page = PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<TspDrivingRecord> records = tspDrivingRecordMapper.selectList(wrapper);
        List<String> ids = records.stream().map(TspDrivingRecord::getId).collect(Collectors.toList());
        Map<String, List<TspDrivingDept>> map = new HashMap<>();
        if (StringUtils.isNotEmpty(ids)) {
            List<TspDrivingDept> drivingDepts = tspDrivingDeptMapper.selectList(new LambdaQueryWrapper<TspDrivingDept>()
                    .in(TspDrivingDept::getRecordId, ids).orderByAsc(TspDrivingDept::getRecordId, TspDrivingDept::getSortNo));
            map = drivingDepts.stream().collect(Collectors.groupingBy(TspDrivingDept::getRecordId));
        }
        Map<String, List<TspDrivingDept>> finalMap = map;
        List<TspDrivingRecordVo> recordVos = records.stream().map(t -> {
            TspDrivingRecordVo recordVo = new TspDrivingRecordVo();
            BeanUtil.copyProperties(t, recordVo);
            if (finalMap.containsKey(t.getId())) {
                recordVo.setTspDrivingDepts(finalMap.get(t.getId()));
            }
            return recordVo;
        }).collect(Collectors.toList());
        return new PageResult<>(page, recordVos);
    }

    /**
     * 新增行车记录
     *
     * @param dto 行车记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertTspDrivingRecord(TspDrivingRecordDto dto) {
        if (StringUtils.isEmpty(dto.getDeliveryType())) {
            throw new ServiceException("配送类型不能为空");
        }
        if (dto.getDepartureKilo().compareTo(dto.getArrivalKilo()) > 0) {
            throw new ServiceException("发车公里数不能大于收车公里数");
        }
        if (StringUtils.isEmpty(dto.getDeptIds())) {
            throw new ServiceException("途径站点不能为空");
        }
        long count = dto.getDeptIds().stream().distinct().count();
        if (count != dto.getDeptIds().size()) {
            throw new ServiceException("途径站点不能重复");
        }
        BasCust basCust = SecurityUtils.getBasCust();
        TspDrivingRecord tspDrivingRecord = new TspDrivingRecord();
        BeanUtil.copyProperties(dto, tspDrivingRecord);
        tspDrivingRecord.setId(IdUtil.simpleUUID());
        tspDrivingRecord.setSysAccount(basCust.getSysAccount());
        tspDrivingRecord.setCreateTime(DateUtils.getNowDate());
        tspDrivingRecord.setCustId(basCust.getId());
        tspDrivingRecord.setDrivingNo(DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSS) + RandomUtil.randomNumbers(6));
        tspDrivingRecord.setCreateTime(DateUtils.getNowDate());
        tspDrivingRecord.setCreateBy(basCust.getCustName());
        tspDrivingRecord.setDeliveryType(JSONUtil.toJsonStr(dto.getDeliveryType()));
        tspDrivingRecord.setStatus(1);
        List<SysDept> sysDepts = sysDeptMapper.selectList(new LambdaQueryWrapper<SysDept>()
                .eq(SysDept::getSysAccount, basCust.getSysAccount())
                .in(SysDept::getDeptId, dto.getDeptIds()));
        int[] sortNo = {1};
        List<TspDrivingDept> tspDrivingDepts = sysDepts.stream().map(t -> {
            TspDrivingDept tspDrivingDept = new TspDrivingDept();
            BeanUtil.copyProperties(t, tspDrivingDept);
            tspDrivingDept.setSortNo(sortNo[0]);
            tspDrivingDept.setId(IdUtil.randomUUID());
            tspDrivingDept.setRecordId(tspDrivingRecord.getId());
            tspDrivingDept.setSysAccount(basCust.getSysAccount());
            tspDrivingDept.setCreateTime(DateUtils.getNowDate());
            tspDrivingDept.setCreateBy(basCust.getCustName());
            sortNo[0]++;
            return tspDrivingDept;
        }).collect(Collectors.toList());
        tspDrivingDeptService.saveBatch(tspDrivingDepts);
        if (StringUtils.isNotEmpty(dto.getImages())) {
            List<BasFiles> basFiles = dto.getImages().stream().map(t -> {
                BasFiles basFile = new BasFiles();
                basFile.setId(IdUtil.randomUUID());
                basFile.setFileType(t.getType());
                basFile.setFileUrl(t.getImage());
                basFile.setRelationId(tspDrivingRecord.getId());
                basFile.setSysAccount(basCust.getSysAccount());
                basFile.setCreateTime(DateUtils.getNowDate());
                return basFile;
            }).collect(Collectors.toList());
            basFilesService.saveBatch(basFiles);
        }
        tspDrivingTrackMapper.insertTspDrivingTrack(buildTrack(tspDrivingRecord.getId(), 2, "", basCust));
        return tspDrivingRecordMapper.insertTspDrivingRecord(tspDrivingRecord);
    }

    /**
     * 写行车记录日志
     *
     * @param recordId
     * @param status
     * @param cust
     * @return
     */
    private TspDrivingTrack buildTrack(String recordId, Integer status, String reason, BasCust cust) {
        TspDrivingTrack tspDrivingTrack = new TspDrivingTrack();
        tspDrivingTrack.setId(IdUtil.simpleUUID());
        tspDrivingTrack.setRecordId(recordId);
        tspDrivingTrack.setStatus(status);
        tspDrivingTrack.setOpUserId(cust.getId());
        tspDrivingTrack.setOpUserName(cust.getCustName());
        tspDrivingTrack.setOpUserAvatar(cust.getAvatar());
        if (status == 1) {
            tspDrivingTrack.setOpCentent("用户主动取消");
        } else if (status == 2) {
            tspDrivingTrack.setOpCentent("用户提交");
        } else if (status == 3) {
            tspDrivingTrack.setOpCentent("审核通过");
        } else if (status == 4) {
            tspDrivingTrack.setOpCentent("订单完成");
        } else if (status == 5) {
            tspDrivingTrack.setOpCentent("修改上报内容");
        } else if (status == 6) {
            tspDrivingTrack.setOpCentent("审核未通过:" + reason);
        }
        tspDrivingTrack.setOpDate(DateUtils.getTime());
        tspDrivingTrack.setSysAccount(cust.getSysAccount());
        return tspDrivingTrack;
    }

    /**
     * 修改行车记录
     *
     * @param dto 行车记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateTspDrivingRecord(TspDrivingRecordDto dto) {
        if (StringUtils.isEmpty((dto.getId()))) {
            throw new ServiceException("id不能为空");
        }
        if (dto.getDepartureKilo().compareTo(dto.getArrivalKilo()) > 0) {
            throw new ServiceException("发车公里数不能大于收车公里数");
        }
        if (StringUtils.isEmpty(dto.getDeptIds())) {
            throw new ServiceException("途径站不能为空");
        }
        TspDrivingRecord oldRecord = tspDrivingRecordMapper.selectTspDrivingRecordById(dto.getId());
        if (oldRecord.getStatus() != 1) {
            throw new ServiceException("当前状态不能修改");
        }
        BasCust basCust = SecurityUtils.getBasCust();
        TspDrivingRecord tspDrivingRecord = new TspDrivingRecord();
        BeanUtil.copyProperties(dto, tspDrivingRecord);
        tspDrivingRecord.setDeliveryType(JSONUtil.toJsonStr(dto.getDeliveryType()));
        tspDrivingRecord.setUpdateTime(DateUtils.getNowDate());
        tspDrivingDeptMapper.delete(new LambdaQueryWrapper<TspDrivingDept>()
                .eq(TspDrivingDept::getSysAccount, basCust.getSysAccount())
                .eq(TspDrivingDept::getRecordId, dto.getId()));
        List<SysDept> sysDepts = sysDeptMapper.selectList(new LambdaQueryWrapper<SysDept>()
                .eq(SysDept::getSysAccount, basCust.getSysAccount())
                .in(SysDept::getDeptId, dto.getDeptIds()));
        int[] sortNo = {1};
        List<TspDrivingDept> tspDrivingDepts = sysDepts.stream().map(t -> {
            TspDrivingDept tspDrivingDept = new TspDrivingDept();
            BeanUtil.copyProperties(t, tspDrivingDept);
            tspDrivingDept.setSortNo(sortNo[0]);
            tspDrivingDept.setId(IdUtil.randomUUID());
            tspDrivingDept.setRecordId(tspDrivingRecord.getId());
            tspDrivingDept.setSysAccount(basCust.getSysAccount());
            tspDrivingDept.setCreateTime(DateUtils.getNowDate());
            tspDrivingDept.setCreateBy(basCust.getCustName());
            sortNo[0]++;
            return tspDrivingDept;
        }).collect(Collectors.toList());
        tspDrivingDeptService.saveBatch(tspDrivingDepts);
        tspDrivingTrackMapper.insertTspDrivingTrack(buildTrack(tspDrivingRecord.getId(), 5, "", basCust));
        return tspDrivingRecordMapper.updateTspDrivingRecord(tspDrivingRecord);
    }

    /**
     * 批量删除行车记录
     *
     * @param ids 需要删除的行车记录主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteTspDrivingRecordByIds(String[] ids) {
        TspDrivingRecord oldRecord = tspDrivingRecordMapper.selectTspDrivingRecordById(ids[0]);
        if (oldRecord.getStatus() != 1) {
            throw new ServiceException("当前状态记录不能删除");
        }
        tspDrivingDeptMapper.delete(new LambdaQueryWrapper<TspDrivingDept>()
                .in(TspDrivingDept::getRecordId, Arrays.asList(ids)));
        return tspDrivingRecordMapper.deleteTspDrivingRecordByIds(ids);
    }

    /**
     * 删除行车记录信息
     *
     * @param id 行车记录主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteTspDrivingRecordById(String id) {
        TspDrivingRecord oldRecord = tspDrivingRecordMapper.selectTspDrivingRecordById(id);
        if (oldRecord.getStatus() != 1) {
            throw new ServiceException("当前状态记录不能删除");
        }
        tspDrivingDeptMapper.delete(new LambdaQueryWrapper<TspDrivingDept>()
                .eq(TspDrivingDept::getRecordId, id));
        return tspDrivingRecordMapper.deleteTspDrivingRecordById(id);
    }

    /**
     * 导出行车记录表
     *
     * @param dto
     * @return
     */
    @Override
    public List<ExportDrivingRecordVo> exportTspDrivingRecordList(QryDrivingRecordDto dto) {
        BasCust cust = SecurityUtils.getBasCust();
        QueryWrapper<TspDrivingRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("sys_account", cust.getSysAccount())
                .eq("cust_id", cust.getId());
        if (dto.getStatus() != 0) {
            wrapper.eq("status", dto.getStatus());
        }
        if (StringUtils.isNotEmpty(dto.getBeginDt())) {
            wrapper.ge("driving_date", dto.getBeginDt());
        }
        if (StringUtils.isNotEmpty(dto.getEndDt())) {
            wrapper.le("driving_date", dto.getEndDt() + " 23:59:59");
        }
        if (StringUtils.isNotEmpty(dto.getKeyWord())) {
            wrapper.and(qw -> qw.eq("driver_name", dto.getKeyWord()).or()
                    .eq("driver_mobile", dto.getKeyWord()).or()
                    .eq("vehicel_number", dto.getKeyWord()).or()
                    .eq("driving_no", dto.getKeyWord()));
        }
        List<TspDrivingRecord> records = tspDrivingRecordMapper.selectList(wrapper);
        List<String> ids = records.stream().map(TspDrivingRecord::getId).collect(Collectors.toList());
        Map<String, List<TspDrivingDept>> map = new HashMap<>();
        if (StringUtils.isNotEmpty(ids)) {
            List<TspDrivingDept> drivingDepts = tspDrivingDeptMapper.selectList(new LambdaQueryWrapper<TspDrivingDept>()
                    .in(TspDrivingDept::getRecordId, ids).orderByAsc(TspDrivingDept::getRecordId, TspDrivingDept::getSortNo));
            map = drivingDepts.stream().collect(Collectors.groupingBy(TspDrivingDept::getRecordId));
        }
        Map<String, List<TspDrivingDept>> finalMap = map;
        List<ExportDrivingRecordVo> recordVos = records.stream().map(t -> {
            ExportDrivingRecordVo recordVo = new ExportDrivingRecordVo();
            BeanUtil.copyProperties(t, recordVo);
            if (finalMap.containsKey(t.getId())) {
                StringJoiner routeSite = new StringJoiner(",");
                finalMap.get(t.getId()).forEach(item -> {
                    routeSite.add(item.getDeptName());
                });
                recordVo.setRouteSite(routeSite.toString());
            }
            return recordVo;
        }).collect(Collectors.toList());
        return recordVos;
    }

    /**
     * 上传行车记录图片
     *
     * @param images
     * @param id
     * @param type
     * @return
     */
    @Override
    public Boolean addImages(String[] images, String id, Integer type) {
        BasCust cust = SecurityUtils.getBasCust();
        if (StringUtils.isEmpty(images)) {
            throw new ServiceException("图片列表不能为空");
        }
        List<BasFiles> basFiles = Stream.of(images).map(t -> {
            BasFiles basFile = new BasFiles();
            basFile.setId(IdUtil.randomUUID());
            basFile.setFileType(type);
            basFile.setFileUrl(t);
            basFile.setRelationId(id);
            basFile.setSysAccount(cust.getSysAccount());
            basFile.setCreateTime(DateUtils.getNowDate());
            return basFile;
        }).collect(Collectors.toList());
        return basFilesService.saveBatch(basFiles);
    }

    /**
     * 查询行车记录图片
     *
     * @param id
     * @param type
     * @return
     */
    @Override
    public List<String> getImages(String id, Integer type) {
        BasCust cust = SecurityUtils.getBasCust();
        List<BasFiles> list = basFilesMapper.selectList(new LambdaQueryWrapper<BasFiles>()
                .eq(BasFiles::getSysAccount, cust.getSysAccount())
                .eq(BasFiles::getRelationId, id)
                .eq(BasFiles::getFileType, type));
        return list.stream().map(BasFiles::getFileUrl).collect(Collectors.toList());
    }

    /**
     * 获取车次
     *
     * @param drivingDate
     * @return
     */
    @Override
    public String getTrainNum(String drivingDate) {
        BasCust cust = SecurityUtils.getBasCust();
        if (StringUtils.isEmpty(drivingDate)) {
            throw new ServiceException("日期不能为空");
        }
        long count = tspDrivingRecordMapper.selectCount(new LambdaQueryWrapper<TspDrivingRecord>()
                .eq(TspDrivingRecord::getSysAccount, cust.getSysAccount())
                .eq(TspDrivingRecord::getDrivingDate, drivingDate)
                .ne(TspDrivingRecord::getStatus, 4));
        return "第" + (count + 1) + "趟";
    }

    /**
     * 统计
     *
     * @param beginDt 开始日期
     * @param endDt   结束日期
     * @param type    1.司机 2.车辆 3.站点 4.线路 5.车队
     * @return
     */
    @Override
    public List<TspDrivingRecordCountVo> count(String beginDt, String endDt, Integer type) {
        BasCust cust = SecurityUtils.getBasCust();
        Map<String, List<TspDrivingRecord>> map = new HashMap<>();
        List<TspDrivingRecordCountVo> retVos = new ArrayList<>();
        switch (type) {
            case 1:
            case 2:
            case 4:
                List<TspDrivingRecord> drivingRecords = tspDrivingRecordMapper.selectList(new LambdaQueryWrapper<TspDrivingRecord>()
                        .eq(TspDrivingRecord::getSysAccount, cust.getSysAccount())
                        .ge(TspDrivingRecord::getDrivingDate, beginDt)
                        .le(TspDrivingRecord::getDrivingDate, endDt));
                if (type == 1) {
                    map = drivingRecords.stream().collect(Collectors.groupingBy(TspDrivingRecord::getVehicelNumber));
                } else if (type == 2) {
                    map = drivingRecords.stream().collect(Collectors.groupingBy(TspDrivingRecord::getDriverName));
                } else {
                    map = drivingRecords.stream().collect(Collectors.groupingBy(TspDrivingRecord::getProjType));
                }
                break;
            case 3:
                List<TspDrivingRecord> stations = tspDrivingRecordMapper.selectJoinList(TspDrivingRecord.class, new MPJLambdaWrapper<TspDrivingRecord>()
                        .select(TspDrivingRecord::getDepartureKilo, TspDrivingRecord::getArrivalKilo, TspDrivingRecord::getCargoCnt, TspDrivingRecord::getWeight,
                                TspDrivingRecord::getAddOil, TspDrivingRecord::getAddOilFee, TspDrivingRecord::getExpresswayFee, TspDrivingRecord::getUreaFee,
                                TspDrivingRecord::getOtherFee)
                        .selectAs(TspDrivingDept::getDeptName, TspDrivingRecord::getRemark)
                        .rightJoin(TspDrivingDept.class, TspDrivingDept::getRecordId, TspDrivingRecord::getId)
                        .eq(TspDrivingRecord::getSysAccount, cust.getSysAccount())
                        .ge(TspDrivingRecord::getDrivingDate, beginDt)
                        .le(TspDrivingRecord::getDrivingDate, endDt));
                map = stations.stream().collect(Collectors.groupingBy(TspDrivingRecord::getRemark));
                break;
            case 5:
                List<TspDrivingRecord> fleets = tspDrivingRecordMapper.selectJoinList(TspDrivingRecord.class, new MPJLambdaWrapper<TspDrivingRecord>()
                        .select(TspDrivingRecord::getDepartureKilo, TspDrivingRecord::getArrivalKilo, TspDrivingRecord::getCargoCnt, TspDrivingRecord::getWeight,
                                TspDrivingRecord::getAddOil, TspDrivingRecord::getAddOilFee, TspDrivingRecord::getExpresswayFee, TspDrivingRecord::getUreaFee,
                                TspDrivingRecord::getOtherFee)
                        .selectAs(BasTruckInfo::getFleet, TspDrivingRecord::getRemark)
                        .leftJoin(BasTruckInfo.class, BasTruckInfo::getPlateNumber, TspDrivingRecord::getVehicelNumber)
                        .eq(TspDrivingRecord::getSysAccount, cust.getSysAccount())
                        .ge(TspDrivingRecord::getDrivingDate, beginDt)
                        .le(TspDrivingRecord::getDrivingDate, endDt));
                fleets.forEach(t -> {
                    if (StringUtils.isEmpty(t.getRemark())) {
                        t.setRemark("无车队信息");
                    }
                });
                map = fleets.stream().collect(Collectors.groupingBy(TspDrivingRecord::getRemark));
        }
        for (Map.Entry<String, List<TspDrivingRecord>> entry : map.entrySet()) {
            TspDrivingRecordCountVo countVo = new TspDrivingRecordCountVo();
            countVo.setItemName(entry.getKey());
            BigDecimal kilometre = BigDecimal.ZERO;
            BigDecimal weight = BigDecimal.ZERO;
            BigDecimal addOil = BigDecimal.ZERO;
            BigDecimal addOilFee = BigDecimal.ZERO;
            BigDecimal expresswayFee = BigDecimal.ZERO;
            BigDecimal ureaFee = BigDecimal.ZERO;
            BigDecimal otherFee = BigDecimal.ZERO;
            int cargoCnt = 0;
            for (TspDrivingRecord record : entry.getValue()) {
                kilometre = kilometre.add(record.getArrivalKilo().subtract(record.getDepartureKilo()));
                weight = weight.add(record.getWeight());
                addOil = addOil.add(record.getAddOil());
                addOilFee = addOilFee.add(record.getAddOilFee());
                expresswayFee = expresswayFee.add(record.getExpresswayFee());
                ureaFee = ureaFee.add(record.getUreaFee());
                otherFee = otherFee.add(record.getOtherFee());
                cargoCnt = cargoCnt + record.getCargoCnt();
            }
            countVo.setKilometre(kilometre);
            countVo.setWeight(weight);
            countVo.setAddOil(addOil);
            countVo.setAddOilFee(addOilFee);
            countVo.setExpresswayFee(expresswayFee);
            countVo.setUreaFee(ureaFee);
            countVo.setOtherFee(otherFee);
            countVo.setCargoCnt(cargoCnt);
            retVos.add(countVo);
        }
        return retVos;
    }

    /**
     * 操作行车记录
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean opRecord(OpDrivingRecordDto dto) {
        TspDrivingRecord record = tspDrivingRecordMapper.selectOne(new LambdaQueryWrapper<TspDrivingRecord>()
                .eq(TspDrivingRecord::getId, dto.getRecordId()));
        BasCust basCust = SecurityUtils.getBasCust();
        if (dto.getStatus() == 6 && StringUtils.isEmpty(dto.getReason())) {
            throw new ServiceException("拒绝原因不能为空");
        }
        if (dto.getStatus() == 1 && record.getStatus() != 2) {
            throw new ServiceException("当前状态不能取消");
        }
        if ((dto.getStatus() == 3 || dto.getStatus() == 6) && record.getStatus() != 1) {
            throw new ServiceException("当前状态不能审核");
        }
        if (dto.getStatus() == 4 && record.getStatus() != 2) {
            throw new ServiceException("当前状态不能完成");
        }
        TspDrivingRecord upRecord = new TspDrivingRecord();
        upRecord.setId(dto.getRecordId());
        upRecord.setUpdateTime(DateUtils.getNowDate());
        if (dto.getStatus() == 1 || dto.getStatus() == 6) {
            upRecord.setStatus(4);
        } else if (dto.getStatus() == 3) {
            upRecord.setStatus(2);
        } else if (dto.getStatus() == 4) {
            upRecord.setStatus(3);
        }
        tspDrivingTrackMapper.insertTspDrivingTrack(buildTrack(dto.getRecordId(), dto.getStatus(), dto.getReason(), basCust));
        return tspDrivingRecordMapper.updateById(upRecord) > 0;
    }

}
